import os
import json
from bs4 import BeautifulSoup

# 读取HTML文件
with open('data2.txt', 'r', encoding='utf-8') as f:
    html_content = f.read()

# 解析HTML
soup = BeautifulSoup(html_content, 'html.parser')

# 找到所有的tr标签
tr_list = soup.find_all('tr', height='45')

# 存储结果的列表
flight_data = []

# 星期映射字典
weekday_map = {
    '1': 'Monday',
    '2': 'Tuesday',
    '3': 'Wednesday',
    '4': 'Thursday',
    '5': 'Friday',
    '6': 'Saturday',
    '7': 'Sunday'
}

# 遍历tr标签（跳过表头行）
for i, tr in enumerate(tr_list):
    # 跳过表头行（前两行）
    if i < 2:
        continue
    
    # 获取td标签
    td_list = tr.find_all('td')
    
    # 确保有足够的td标签
    if len(td_list) >= 6:
        # 提取航班信息
        flight_number = td_list[0].text.strip()
        departure_city = td_list[1].text.strip()
        arrival_city = td_list[2].text.strip()
        departure_time = td_list[3].text.strip()
        schedule = td_list[4].text.strip()
        product_info = td_list[5].text.strip()
        
        # 处理适用产品
        applicable_products = []
        if '/2666' in product_info:
            applicable_products = ['666', '2666']
        elif product_info == '666':
            applicable_products = ['666']
        elif product_info == '2666':
            applicable_products = ['2666']
        
        # 处理排期（转换为星期列表）
        weekdays = []
        for day in schedule:
            if day in weekday_map:
                weekdays.append(weekday_map[day])
        
        # 构建航班数据字典
        flight_dict = {
            'flight_number': flight_number,
            'departure_city': departure_city,
            'arrival_city': arrival_city,
            'departure_time': departure_time,
            'schedule': schedule,
            'weekdays': weekdays,
            'applicable_products': applicable_products
        }
        
        flight_data.append(flight_dict)

# 将数据保存为JSON文件
with open('flight_dataxia.json', 'w', encoding='utf-8') as f:
    json.dump(flight_data, f, ensure_ascii=False, indent=2)

print(f"转换完成！共处理了 {len(flight_data)} 条航班数据。")
print("JSON文件已保存为：flight_data.json")